from typing import List
import logging
from fastapi import APIRouter, HTTPException, Path, Query
from app.schemas.warehouse_goods_schemas import (
    WarehouseGoodsCreate,
    WarehouseGoodsUpdate,
    WarehouseGoodsResponse
)
from app.services.warehouse_goods_service import WarehouseGoodsService
from tortoise.exceptions import DoesNotExist, IntegrityError

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/", response_model=WarehouseGoodsResponse, status_code=201)
async def add_goods_to_warehouse(
    warehouse_goods: WarehouseGoodsCreate
):
    """
    添加商品到仓库
    
    Args:
        warehouse_goods: 仓库商品关系创建模型
        
    Returns:
        WarehouseGoodsResponse: 创建成功的仓库商品关系信息
        
    Raises:
        HTTPException: 
            - 400: 数据验证失败
            - 404: 仓库或商品不存在
            - 409: 商品已存在于该仓库
            - 500: 服务器内部错误
    """
    try:
        logger.info(f"接收添加商品到仓库请求: {warehouse_goods.model_dump()}")
        result = await WarehouseGoodsService.add_goods_to_warehouse(warehouse_goods)
        logger.info(f"商品添加成功: inventory_id={result['id']}")
        return result
    except DoesNotExist as e:
        logger.error(f"添加商品失败(记录不存在): {str(e)}")
        raise HTTPException(status_code=404, detail=str(e))
    except IntegrityError as e:
        logger.error(f"添加商品失败(完整性约束): {str(e)}")
        raise HTTPException(status_code=409, detail=str(e))
    except ValueError as e:
        logger.error(f"添加商品失败(数据验证): {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"添加商品失败(未知错误): {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@router.get(
    "/",
    response_model=List[WarehouseGoodsResponse],
    responses={404: {"description": "No inventory records found"}}
)
async def get_warehouse_inventory(
    warehouse_id: int | None = Query(None, ge=0, description="仓库ID（可选）"),
    goods_id: int | None = Query(None, ge=0, description="商品ID（可选）"),
    skip: int = Query(0, ge=0, description="分页偏移量"),
    limit: int = Query(10, ge=1, le=100, description="分页大小")
):
    """
    获取库存清单，支持按仓库ID和商品ID筛选
    
    Args:
        warehouse_id: 仓库ID，可选
        goods_id: 商品ID，可选
        skip: 分页偏移量，默认0
        limit: 分页大小，默认10，最大100
        
    Returns:
        List[WarehouseGoodsResponse]: 库存列表
        
    Raises:
        HTTPException: 
            - 404: 未找到符合条件的记录
            - 400: 参数验证失败
    """
    try:
        inventory = await WarehouseGoodsService.get_inventory_list(
            warehouse_id=warehouse_id,
            goods_id=goods_id,
            skip=skip,
            limit=limit
        )
        if not inventory and skip == 0:
            raise HTTPException(
                status_code=404,
                detail="No inventory records found with the specified criteria"
            )
        return inventory
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")

@router.put(
    "/{inventory_id}",
    response_model=WarehouseGoodsResponse,
    responses={
        404: {"description": "Inventory record not found"},
        400: {"description": "Invalid update data"}
    }
)
async def update_inventory(
    inventory_id: int = Path(..., title="库存记录ID", gt=0),
    update_data: WarehouseGoodsUpdate = None
):
    """
    更新库存信息
    
    Args:
        inventory_id: 库存记录ID，必须大于0
        update_data: 更新的库存信息
        
    Returns:
        WarehouseGoodsResponse: 更新后的库存信息
        
    Raises:
        HTTPException: 
            - 400: 更新数据验证失败
            - 404: 库存记录不存在
            - 500: 服务器内部错误
    """
    try:
        logger.info(f"接收更新库存请求: inventory_id={inventory_id}, update_data={update_data.model_dump() if update_data else None}")
        
        if not update_data:
            logger.error("更新数据为空")
            raise HTTPException(status_code=400, detail="Update data is required")
            
        updated_inventory = await WarehouseGoodsService.update_inventory(
            inventory_id, update_data
        )
        
        if not updated_inventory:
            logger.warning(f"库存记录不存在: inventory_id={inventory_id}")
            raise HTTPException(
                status_code=404,
                detail=f"Inventory record with id {inventory_id} not found"
            )
            
        logger.info(f"库存更新成功: inventory_id={inventory_id}")
        return updated_inventory
        
    except ValueError as e:
        logger.error(f"更新库存失败(数据验证): {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"更新库存失败(未知错误): {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to update inventory: {str(e)}")

@router.get(
    "/{inventory_id}",
    response_model=WarehouseGoodsResponse,
    responses={404: {"description": "Inventory record not found"}}
)
async def get_inventory(
    inventory_id: int = Path(..., title="库存记录ID", gt=0)
):
    """
    获取单个库存记录详情
    
    Args:
        inventory_id: 库存记录ID，必须大于0
        
    Returns:
        WarehouseGoodsResponse: 库存记录详情
        
    Raises:
        HTTPException: 
            - 404: 库存记录不存在
    """
    try:
        inventory = await WarehouseGoodsService.get_inventory(inventory_id)
        if not inventory:
            raise HTTPException(
                status_code=404,
                detail=f"Inventory record with id {inventory_id} not found"
            )
        return inventory
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")